<template>
  <div class="distribution-manage">
    <!-- 🔍 搜索/筛选区（保留原功能） -->
    <div class="top-row">
      <el-input
        v-model="searchForm.keywordInput"
        placeholder="请输入分销主体（名称）"
        clearable
        class="search-item"
      />
      <el-input
        v-model="searchForm.phoneInput"
        placeholder="请输入手机号"
        clearable
        class="search-item"
      />
      <el-select
        v-model="searchForm.typeInput"
        placeholder="身份类型"
        clearable
        class="search-item"
      >
        <el-option label="商家" value="merchant" />
        <el-option label="个人" value="user" />
      </el-select>
      <el-select
        v-model="searchForm.statusInput"
        placeholder="打款状态"
        clearable
        class="search-item"
      >
        <el-option label="待打款" value="pending" />
        <el-option label="已打款" value="paid" />
      </el-select>
      <el-button type="primary" @click="handleSearch" class="search-item-button"> 搜索 </el-button>
    </div>

    <!-- 📋 表格（提现管理风格） -->
    <div class="table-wrapper">
      <el-table
        v-loading="loading"
        :data="paginatedData"
        border
        style="width: 100%"
        v-if="paginatedData.length > 0"
      >
        <!-- 序号 -->
        <el-table-column label="序号" width="70" align="center">
          <template #default="{ $index }">
            {{ (currentPage - 1) * pageSize + $index + 1 }}
          </template>
        </el-table-column>

        <!-- 分销主体（含身份） -->
        <el-table-column label="分销主体" min-width="220">
          <template #default="{ row }">
            <span
              class="type-chip"
              :class="row.type === 'merchant' ? 'type-merchant' : 'type-user'"
            >
              {{ row.type === 'merchant' ? '商家' : '个人' }}
            </span>
            <span class="subject-text">{{ row.name }}</span>
          </template>
        </el-table-column>

        <!-- 手机号（复制） -->
        <el-table-column label="手机号" min-width="160">
          <template #default="{ row }">
            <span>{{ row.phone || '-' }}</span>
            <el-button
              v-if="row.phone"
              text
              size="small"
              class="copy-btn"
              @click="copyText(row.phone, '手机号')"
            >
              <el-icon><DocumentCopy /></el-icon>
            </el-button>
          </template>
        </el-table-column>

        <!-- 收款信息（提现管理风格） -->
        <el-table-column label="收款信息" min-width="380">
          <template #default="{ row }">
            <div class="payline">
              <span>收款人：{{ row.withdrawInfo.receiver || '-' }}</span>
              <span class="divider">|</span>
              <span>账户：{{ row.withdrawInfo.account || '-' }}</span>
              <span class="divider">|</span>
              <span>开户行：{{ row.withdrawInfo.bank || '-' }}</span>
              <el-button
                v-if="row.withdrawInfo.account"
                text
                size="small"
                class="copy-btn"
                @click="copyText(row.withdrawInfo.account, '账户信息')"
              >
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>

        <!-- 当前状态 -->
        <el-table-column label="当前状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'pending' ? 'warning' : 'success'">
              {{ row.status === 'pending' ? '待打款' : '已打款' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" fixed="right" min-width="150">
          <template #default="{ row }">
            <el-button size="small" @click="showDetail(row)">详情</el-button>
            <el-button
              size="small"
              type="primary"
              :disabled="row.status === 'paid' || row.pendingAmount <= 0"
              @click="confirmPayout(row)"
            >
              {{ row.status === 'pending' ? '打款完成' : '已打款' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-else class="no-data">暂无数据</div>
    </div>

    <!-- 📑 分页 -->
    <div class="pagination-wrap">
      <el-pagination
        v-if="filteredData.length > 0"
        background
        layout="prev, pager, next"
        :total="filteredData.length"
        :page-size="pageSize"
        v-model:current-page="currentPage"
      />
    </div>

    <!--  详情弹窗  -->
    <el-dialog
      v-model="detailDialog.visible"
      :title="detailDialog.title"
      width="780px"
      class="detail-dialog"
    >
      <div v-if="detailDialog.row" class="detail-content">
        <!-- 基础信息 -->
        <div class="base-grid">
          <div class="item">
            <span class="label">身份类型：</span>
            <span class="val">{{ detailDialog.row.type === 'merchant' ? '商家' : '个人' }}</span>
          </div>
          <div class="item">
            <span class="label">分销主体：</span>
            <span class="val">{{ detailDialog.row.name }}</span>
          </div>
          <div class="item">
            <span class="label">手机号：</span>
            <span class="val">
              {{ detailDialog.row.phone || '-' }}
              <el-button
                v-if="detailDialog.row.phone"
                text
                size="small"
                class="copy-btn"
                @click="copyText(detailDialog.row.phone, '手机号')"
              >
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </span>
          </div>
          <div class="item span-2">
            <span class="label">收款信息：</span>
            <span class="val">
              收款人：{{ detailDialog.row.withdrawInfo.receiver || '-' }}
              <span class="divider">|</span>
              账户：{{ detailDialog.row.withdrawInfo.account || '-' }}
              <span class="divider">|</span>
              开户行：{{ detailDialog.row.withdrawInfo.bank || '-' }}
              <el-button
                v-if="detailDialog.row.withdrawInfo.account"
                text
                size="small"
                class="copy-btn"
                @click="copyText(detailDialog.row.withdrawInfo.account, '账户信息')"
              >
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </span>
          </div>
        </div>

        <!-- 金额卡片 -->
        <div class="amount-cards">
          <div class="card total">
            <div class="card-title">分销总金额</div>
            <div class="card-num">￥{{ detailDialog.row.totalAmount.toFixed(2) }}</div>
          </div>
          <div class="card pending">
            <div class="card-title">待打款</div>
            <div class="card-num">￥{{ detailDialog.row.pendingAmount.toFixed(2) }}</div>
          </div>
          <div class="card paid">
            <div class="card-title">已打款</div>
            <div class="card-num">￥{{ detailDialog.row.paidAmount.toFixed(2) }}</div>
          </div>
        </div>

        <!-- 打款记录 -->
        <div class="history-wrap">
          <div class="history-title">打款记录</div>
          <el-table
            :data="detailDialog.row.payHistory"
            size="small"
            border
            height="240"
            v-if="detailDialog.row.payHistory.length > 0"
          >
            <el-table-column prop="id" label="编号" width="120" />
            <el-table-column label="金额" width="160">
              <template #default="{ row }">￥{{ row.amount.toFixed(2) }}</template>
            </el-table-column>
            <el-table-column prop="time" label="时间" />
            <el-table-column prop="remark" label="备注" width="160" />
          </el-table>
          <div v-else class="no-history">暂无打款记录</div>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DocumentCopy } from '@element-plus/icons-vue'
import {
  getDistributors,
  markPayout,
  type Distributor,
  type DistributorStatus,
  type DistributorType
} from '@/api/distribution'

/* 搜索表单（缓存） */
const searchForm = ref({
  keywordInput: '',
  phoneInput: '',
  typeInput: '' as '' | DistributorType,
  statusInput: '' as '' | DistributorStatus
})

/* 过滤参数 */
const filterKeyword = ref('')
const filterPhone = ref('')
const filterType = ref<DistributorType | ''>('')
const filterStatus = ref<DistributorStatus | ''>('')

/* 列表与分页 */
const loading = ref(false)
const list = ref<Distributor[]>([])
const currentPage = ref(1)
const pageSize = 10

/* 详情弹窗 */
const detailDialog = ref<{
  visible: boolean
  title: string
  row: Distributor | null
}>({
  visible: false,
  title: '分销详情',
  row: null
})

/* 过滤数据 */
const filteredData = computed(() => {
  return list.value.filter(item => {
    const matchName = filterKeyword.value
      ? item.name?.toLowerCase().includes(filterKeyword.value.toLowerCase())
      : true
    const matchPhone = filterPhone.value ? (item.phone || '').includes(filterPhone.value) : true
    const matchType = filterType.value ? item.type === filterType.value : true
    const matchStatus = filterStatus.value ? item.status === filterStatus.value : true
    return matchName && matchPhone && matchType && matchStatus
  })
})

/* 分页数据 */
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  return filteredData.value.slice(start, start + pageSize)
})

/* 搜索 */
function handleSearch() {
  filterKeyword.value = searchForm.value.keywordInput.trim()
  filterPhone.value = searchForm.value.phoneInput.trim()
  filterType.value = searchForm.value.typeInput
  filterStatus.value = searchForm.value.statusInput
  currentPage.value = 1
}

/* 加载数据 */
async function loadData() {
  loading.value = true
  try {
    list.value = await getDistributors()
  } finally {
    loading.value = false
  }
}

/* 显示详情 */
function showDetail(row: Distributor) {
  detailDialog.value = {
    visible: true,
    title: '分销详情',
    row
  }
}

/* 确认打款 */
async function confirmPayout(row: Distributor) {
  try {
    if (row.pendingAmount <= 0) {
      ElMessage.info('无待打款金额')
      return
    }
    await ElMessageBox.confirm(
      `确认将“${row.name}”的待打款（￥${row.pendingAmount.toFixed(2)}）标记为已打款？`,
      '打款确认',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )
    await markPayout(row.id)
    ElMessage.success('打款已完成')
    await loadData()
    if (detailDialog.value.visible && detailDialog.value.row?.id === row.id) {
      const newRow = list.value.find(x => x.id === row.id) || null
      detailDialog.value.row = newRow
    }
  } catch (err: unknown) {
    if (err !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

/* 复制 */
async function copyText(text: string, label = '内容') {
  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text)
    } else {
      const ta = document.createElement('textarea')
      ta.value = text
      ta.style.position = 'fixed'
      ta.style.left = '-9999px'
      document.body.appendChild(ta)
      ta.focus()
      ta.select()
      document.execCommand('copy')
      document.body.removeChild(ta)
    }
    ElMessage.success(`${label}已复制`)
  } catch {
    ElMessage.error('复制失败，请手动选择复制')
  }
}

onMounted(loadData)
</script>

<style scoped>
.distribution-manage {
  padding: 16px;
  --row-cell-padding: 16px; /* ← 你可以自由修改这里，行越高，值越大 */
  display: flex;
  flex-direction: column;
  gap: 16px;
  background: #f5f7fa;
}
:deep(.el-table__body-wrapper td),
:deep(.el-table__header-wrapper th) {
  padding-top: var(--row-cell-padding) !important;
  padding-bottom: var(--row-cell-padding) !important;
}

.search-item {
  min-width: 140px;
  max-width: 220px;
  margin-right: 12px;
}

.search-item-button {
  flex-shrink: 0;
  margin-left: 4px;
}

.table-wrapper {
  overflow-x: auto;
  background: #fff;
  border-radius: 8px;
  padding: 12px 16px;
}

.type-chip {
  display: inline-block;
  padding: 2px 6px;
  border-radius: 6px;
  font-size: 12px;
  margin-right: 8px;
  color: #fff;
}
.type-merchant {
  background: #409eff;
}
.type-user {
  background: #67c23a;
}
.subject-text {
  font-weight: 600;
}
.payline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 6px;
}
.divider {
  color: #bbb;
  margin: 0 2px;
}
.copy-btn {
  margin-left: 4px;
}
.pagination-wrap {
  display: flex;
  justify-content: flex-start;
  margin-top: 12px;
}
.no-data {
  text-align: center;
  padding: 60px 0;
  color: #999;
  font-size: 14px;
}
.detail-dialog :deep(.el-dialog__body) {
  padding-top: 10px;
}
.detail-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.base-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  grid-auto-rows: auto;
  gap: 10px 16px;
}
.base-grid .item {
  display: flex;
  align-items: center;
  min-height: 28px;
}
.base-grid .item.span-2 {
  grid-column: span 2;
}
.label {
  color: #666;
  width: 90px;
  flex-shrink: 0;
}
.val {
  color: #333;
}
.amount-cards {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 12px;
}
.card {
  border: 1px solid #ebeef5;
  border-radius: 10px;
  padding: 14px 16px;
}
.card-title {
  font-size: 12px;
  color: #666;
  margin-bottom: 6px;
}
.card-num {
  font-size: 20px;
  font-weight: 700;
}
.card.total .card-num {
  color: #303133;
}
.card.pending .card-num {
  color: #e6a23c;
}
.card.paid .card-num {
  color: #67c23a;
}
.history-wrap {
  margin-top: 4px;
}
.history-title {
  font-weight: 600;
  margin-bottom: 8px;
}
.no-history {
  text-align: center;
  color: #999;
  padding: 12px 0;
}
@media (max-width: 720px) {
  .amount-cards {
    grid-template-columns: 1fr;
  }
  .base-grid .item.span-2 {
    grid-column: span 1;
  }
}
</style>
